<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function gift_list_page()
{
    @$output = drupal_render(drupal_get_form('gift_list_form'));
    return $output;
}

function gift_assign_page()
{
    @$output = drupal_render(drupal_get_form('gift_assign_form'));
    return $output;
}

function gift_list_form($form, &$form_state)
{
    global $user;
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    $user_info = _get_user_info($user->uid);
    if ($user_info['role'] != '农户') {
        if(empty($form_state['farmer'])){
            $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
            $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
        }else{
            $form['#farmer'] = $form_state['farmer'];
        }
        if(!empty($_GET['special_activities'])){
            $special_activities_title = get_special_activities_title($_GET['special_activities']);
        }
        $form['special_activities'] = array(
            '#type' => 'textfield',
            '#title' => '专项活动',
            '#size' => 32,
            '#maxlength' => 50,
            '#id'=>'special_activities_textfield',
            '#default_value' => $special_activities_title,
        );
    }
    if(!empty($form_state['farmer'])){
        $form['#farmer'] = $form_state['farmer'];
    }
    $form['gift_type'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => '礼物类型',
            1 => '化肥',
            2 => '代金券',
        ),
        '#default_value' => !empty($record) ? $record->gift_type : 0,
    );
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function gift_assign_form($form, &$form_state)
{
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
    $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
    $table['#markup'] = gift_assign_data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    $form['gift_type'] = array(
        '#type' => 'select',
        '#title' => '礼物类型',
        '#options' => array(
            0 => '礼物类型',
            1 => '化肥',
            2 => '代金券',
        ),
        '#default_value' => !empty($record) ? $record->gift_type : 0,
//        '#required' => TRUE,
    );
    $form['quantity'] = array(
        '#type' => 'textfield',
        '#title' => '赠送数量',
        '#default_value' => !empty($record) ? $record->quantity : '',
//        '#required' => TRUE,
    );

    $form['comments'] = array(
        '#type' => 'textarea',
        '#title' => '赠送备注',
        '#default_value' => !empty($record) ? $record->comments : '',
//        '#required' => FALSE,
    );
    $form['gift']['#markup'] = '<a href="javascript:void(0)" onclick="gift_assign()" id="gift_assign" data-toggle="modal" class="gift_assign btn btn-mini btn-primary">分配</a>';
    return $form;
}

function gift_list_form_validate($form, &$form_state)
{
}

function gift_assign_data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info($user->uid);
    $output = '';
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        array('data' => '地址', 'class' => ['essential province city county']),
        array('data' => '农户姓名', 'class' => ['essential farmer']),
    );
    $query = db_select('farmer', 'F')->extend('PagerDefault')->extend('TableSort');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    //地址级别查询
    _address_search_conditon($query,$form_state);
    //模糊条件筛选
    if (!empty($form_state['values']['farmer'])) {//模糊电话号码查询条件
        $query->condition('F.farmer_id', $form_state['values']['farmer'], '=');
    }
    $query->fields('F', array('farmer_id', 'farmer_name'));
    if ($form_state['triggering_element']['#value'] != '查询')
        $query->orderBy('F.timestamp', 'DESC');
    $query->limit(variable_get("list_page_item_number", 5));

    $giftInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    foreach ($giftInfo as $row) {
        $city = $row->city ? ' ' . $row->city : '';
        $county = $row->county ? ' ' . $row->county : '';
        $town = $row->town ? ' ' . $row->town : '';
        $village = $row->village ? ' ' . $row->village : '';
        $rows[] = array(
            array('data' => "<input type='checkbox' class='listViewTableCheck' value ='" . $row->farmer_id . "' name='" . $row->farmer_id . "'/>" . $n++, 'class' => 'essential no'),
            array('data' => $row->province . $city . $county.$town.$village, 'class' => ['integrant essential province city county']),
            array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '">' . $row->farmer_name . "</a>", 'class' => ['essential farmer']),
        );
    }
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    $output .= theme('pager');
    return $output;
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info($user->uid);
    //表头
    if ($user_info['role'] != '农户') {
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => '地址', 'class' => ['essential province city county']),
            isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => '农户姓名', 'class' => ['essential farmer']),
            array('data' => '礼物类型', 'class' => ['essential gift_type']),
            array('data' => '数量', 'class' => ['essential quantity']),
            array('data' => '备注', 'class' => ['essential comments']),
            array('data' => '操作', 'class' => ['essential more']),
        );
    } else {
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => '农户姓名', 'class' => ['essential farmer']),
            array('data' => '礼物类型', 'class' => ['essential gift_type']),
            array('data' => '数量', 'class' => ['essential quantity'], 'field' => 'quantity'),
            array('data' => '备注', 'class' => ['essential comments']),
            array('data' => '操作', 'class' => ['essential more']),
        );
    }
    $output = '';
    $query = db_select('gift', 'G')->extend('PagerDefault')->extend('TableSort');
    $query->join('farmer', 'F', 'G.farmer_id = F.farmer_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    //地址级别查询
    _address_search_conditon($query,$form_state);
    //模糊条件筛选
    if (!empty($form_state['values']['farmer'])) {//模糊电话号码查询条件
        $query->condition('G.farmer_id', $form_state['values']['farmer'], '=');
    }
    if ($user_info['role'] == '农户') {
        $query->condition('G.farmer_id', $user->uid, '=');
    }
    if (!empty($_GET['farmer_id'])) {
        $query->condition('G.farmer_id', $_GET['farmer_id']);
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $query->condition('G.farmer_id', $form_state['farmer']);
    }
    if (!empty($form_state['values']['gift_type'])) {
        $query->condition('G.gift_type', $form_state['values']['gift_type'], '=');
    }
    if (!empty($form_state['values']['farmer_id'])) {
        $query->condition('G.farmer_id', $form_state['values']['farmer_id'], '=');
    }
    //专项活动
    if(!empty($form_state['values']['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('G.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('G.special_activities_id',0, '=');
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('G.special_activities_id',$_GET['special_activities'], '=');
    }
    $query->fields('G');
    $query->fields('F', array('farmer_id', 'farmer_name'));
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('G.timestamp', 'DESC');
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $giftInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    foreach ($giftInfo as $row) {
        if (nonghua_user_access_with_double_permissions('gift', 'manage', $row->gift_id, $row->author_uid, $row->farmer_id)) {
            $disabled = ' class="listViewTableCheck" ';
        } else{
            $disabled = ' disabled="true" ';
        }

        if ($user_info['role'] != '农户') {
            $city = $row->city ? ' ' . $row->city : '';
            $county = $row->county ? ' ' . $row->county : '';
            $town = $row->town ? ' ' . $row->town : '';
            $village = $row->village ? ' ' . $row->village : '';
            $rows[] = array(
                array('data' => "<input type='checkbox'".$disabled." value ='" . $row->gift_id . "' name='" . $row->gift_id . "'/>" . $n++, 'class' => 'essential no'),
                isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => $row->province . $city . $county.$town.$village, 'class' => ['integrant essential province city county']),
                isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?farmer_id=' . $row->farmer_id .'">' . $row->farmer_name . "</a>", 'class' => ['essential farmer']),
                array('data' => $row->gift_type == 1 ? '化肥' : '代金券', 'class' => ['essential gift_type']),
                array('data' => $row->quantity, 'class' => ['essential quantity']),
                array('data' => $row->comments, 'class' => ['essential comments']),
                (isset($form_state['farmer']) && !empty($form_state['farmer'])) ?
                    array('data' => '<a href="' . base_path() . 'gift/edit/' . $row->gift_id . '?' .
                        (isset($form_state['farmer']) && !empty($form_state['farmer']) ? 'farmer_id=' . $form_state['farmer'] : '') .
                        '" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                    array('data' => '<a href="' . base_path() . 'gift/edit/' . $row->gift_id . '"  target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        } else {
            $rows[] = array(
                array('data' => "<input type='checkbox'".$disabled." value ='" . $row->gift_id . "' name='" . $row->gift_id . "'/>" . $n++, 'class' => 'essential no'),
                isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
                array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?farmer_id=' . $row->farmer_id .'">' . $row->farmer_name . "</a>", 'class' => ['essential farmer']),
                array('data' => $row->gift_type == 1 ? '化肥' : '代金券', 'class' => ['essential gift_type']),
                array('data' => $row->quantity, 'class' => ['essential quantity']),
                array('data' => $row->comments, 'class' => ['essential comments']),
                (isset($form_state['farmer']) && !empty($form_state['farmer'])) ?
                    array('data' => '<a href="' . base_path() . 'gift/edit/' . $row->gift_id . '?' .
                        (isset($form_state['farmer']) && !empty($form_state['farmer']) ? 'farmer_id=' . $form_state['farmer'] : '') .
                        '" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                    array('data' => '<a href="' . base_path() . 'gift/edit/' . $row->gift_id . '"  target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        }
    }


    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && user_access('manage gift')) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    $output .= theme('pager');
    return $output;
}

function gift_delete()
{
    ajax_table_delete('gift', 'gift_id');
}